/**
 * Created by levy on 16/4/11.
 * @author truexin
 * @date   2016/07/25
 */
import DetailRow from "../components/detail/ProgressDetail";
import FooterBtn from "../components/detail/FooterBtn";

(function (lf, r, mui) {
    var log = lf.utils.log,
        ajax = lf.utils.ajax,
        doAction = lf.bridgeJs.doAction,
        appAlert = lf.bridgeJs.alert,
        
        processId = lf.utils.getUrlParam('processId', location.search),
        taskName = lf.utils.getUrlParam('taskName', location.search),
        orderId = lf.utils.getUrlParam('orderId', location.search),
        
        flag = lf.utils.getUrlParam('flag', location.search) || lf.approvalInfo.APPROVING, //默认新增可编辑
        isNew = orderId ? false : true; //这里写得不好,其实应该写进flag里,默认是new的...

    // let isApproved = false;//已
    
    //5/11 完成时，为null的，要转换为''，传给后台才不报错
    if (taskName == 'null') taskName = '';
    
    const PDF = 'https://pdf.h5.liefengtech.com/web/viewer.html?file='; //PDF 跳转前缀
    
    //变量存储传向后台的参数
    var ajaxData = {
        taskId: '', //当前步骤taskId
        taskName: '', //有时不从url取
        assignee: '',
        nextOperator: ''//id
    };
    
    /**
     * 接受三个props：
     * name 可选
     * data(必填): "1:一般;2:秘密;3:绝密;4:机密"　
     分隔符可用(,)逗号
     * defaultValue 默认值　可选
     * value 真正的值 可选
     * clickFn 父组件传过来的点击函数 可选
     * fnData 与函数相关的要用的数据 多个作为数组传过来　可选
     */
    var Radio = r.createClass({
        getInitialState: function () {
            return {
                radios: [],
            }
        },
        componentWillMount: function () {
            var props = this.props,
                data = props.data,
                fnData = props.fnData ? props.fnData : [],
                defaultValue = props.defaultValue || -1,
                trueValue = props.value || -1,
                name = props.name || '',
                isNeed = props.isNeed || '',
                readonly = props.readonly,
                str_array = data.indexOf(';') > -1 ? data.split(';') : data.split(','),
                radios;
            
            //log(readonly)
            //log(trueValue)
            
            radios = str_array.map(function (str, i) {
                var array = str.split(':'),
                    value = array[0],
                    text = array[1],
                    className = isNeed ? 'required' : '';
                className += ' mui-btn';
                
                if (!name) //单纯的标签
                    return <label className={className} data-data={fnData[i] || fnData}>{text}</label>
                
                //先为真正的值赋值,新增时才使用default值
                if (str.indexOf(trueValue) > -1 || (isNew && str.indexOf(defaultValue) > -1))
                    className += ' active';
                else if (readonly == 'true' || !isNew) // readonly的未选值不显示
                    className += ' ele-hide'; //未选值不显示
                
                //办理页面即有下一步办理人页面,readonly 字段是可靠的
                if (flag == lf.approvalInfo.APPROVING && readonly == 'true')
                    className += ' readonly';
                
                //input radio通过css来隐藏
                return <span key={'radio-'+i} className={className + ' no-padding'}>
                    <label className="mui-padding" htmlFor={name + i} data-data={fnData[i] || fnData}>{text}</label>
                    <input id={name + i} name={name} type="radio" defaultValue={value} hidden="hidden"/>
                </span>
            });
            
            this.setState({
                radios: radios,
            })
        },
        componentDidMount: function () {
            var node = r.findDOMNode(this.refs.box),
                $btns = $(node).find('.mui-btn'),
                clickFn = this.props.clickFn;
            
            if (isNew || flag == lf.approvalInfo.APPROVING) {
                $btns.not('.readonly').each(function (i, btn) {
                    var $btn = $(this);
                    
                    $btn.on('touchstart', function (e) {
                        
                        var node = e.target;
                        
                        //有可能两种情况：parent()是span，或者是div
                        if (node.parentNode.tagName == 'DIV') {
                            //妈的,zepto没有end()
                            $(node).addClass('active')
                            .siblings().removeClass('active');
                        }
                        else if (node.parentNode.tagName == 'SPAN') {
                            //这种情况下，后面有label的
                            $(node).parent().addClass('active')
                            .siblings().removeClass('active');
                        }
                        
                        clickFn && clickFn(e);
                    });
                    
                    //默认第一个选中
                    if (i == 0)
                        $btn.trigger('touchstart');
                });
            }
            
            //给active的radio赋值
            $btns.filter('.active').find('input[type=radio]').each(function () {
                $(this).attr('checked', true);
            });
        },
        render: function () {
            return (
                <div ref="box" className="box radio-wrapper flex-box-row">
                    {this.state.radios}
                </div>
            );
        }
    });
    
    var DtPicker = r.createClass({
        render: function () {
            var props = this.props,
                inputClass = ' text-right float-right ';
            
            return <input ref="dtpicker" type="text" readOnly placeholder="请选择时间*"
                          className={props.isNeed == 'true' ?  "required" + inputClass : inputClass}
                          value={props.value} name={props.name}/>;
        },
        componentDidMount: function () {
            if (this.props.readonly != 'true') {
                //if(sys == lf.systemFlag.IOS){
                //    var picker = new mui.DtPicker({});
                //}
                
                $(r.findDOMNode(this.refs.dtpicker)).on('tap', function (e) {
                    //去掉系统键盘
                    e.target.focus();
                    var $me = $(this);
                    
                    ////ios
                    //if(sys == lf.systemFlag.IOS){
                    //    picker.show(function (rs) {
                    //        $me.val(rs.text);
                    //        picker.hide();
                    //    });
                    //}
                    //else {
                    //    lf.bridgeJs.datePicker('date_time', function (data) {
                    //        $me.val(data);
                    //    });
                    //}
                    lf.bridgeJs.datePicker('date_time', function (data) {
                        $me.val(data);
                    });
                });
            }
        }
    });
    
    //这里有一个使用DidUpdate的例子
    var NextTask = r.createClass({
        getInitialState: function () {
            return {
                processorList: [],
                radios: [],
            }
        },
        componentWillMount: function () {
            var me = this,
                data = me.props.data, //　宁愿这里报错，什么都不出来　
                datas = [],
                fnDatas = [];
            
            if (data)
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (!item) continue;
                    
                    datas.push(i + ":" + item.displayName);
                    fnDatas.push(item.assignee + '-' + item.name);
                }
            
            this.setState({
                radios: <Radio data={datas.toString()} fnData={fnDatas} clickFn={me.loadProcessorList} test='test'/>,
            })
        },
        loadProcessorList: function (e) {
            var me = this,
                fnData = $(e.target).data('data').split('-'),
                $nextPerson = $('#next-person');

            //结束时隐藏下一步办理人
            if (fnData[1] == 'end')
                $nextPerson.hide();
            else
                $nextPerson.show();
            
            ajaxData.assignee = fnData[0];
            ajaxData.taskName = fnData[1];

            ajax({
                data: {
                    staffId: lf.userInfo.id,
                    taskName: fnData[1],
                    assignee: ajaxData.assignee,
                    orderId: orderId || null,
                },
                success: function (data) {
                    if (data.code != '200') return;

                    me.setState({
                        processorList: data.dataList.map(function (data, i) {
                            return <a key={'person-'+i} className="mui-btn text-dot" data-id={data.id}>{data.name}</a>
                        }),
                    })
                },
            }, lf.api.workflow.processorList)
        },
        render: function () {
            
            return (
                <div id="next" className="">
                    <div className="title white-bg margin-top">选择下一步骤</div>
                    {this.state.radios}
                    <div id="next-person" className="title white-bg margin-top">选择下一步办理人</div>
                    <div ref="personBox" className="box radio-wrapper flex-box-row">
                        {this.state.processorList}
                    </div>
                </div>
            )
        },
        componentDidUpdate: function () {
            var persons = r.findDOMNode(this.refs.personBox).getElementsByTagName('a');
            
            $.each(persons, function (i, item) {
                var $me = $(this);
                
                //touch事件响应快
                $me.on('touchstart', function () {
                    $me.addClass('active').siblings().removeClass('active');
                    
                    ajaxData.nextOperator = $(this).data('id');
                    //alert(ajaxData.nextOperator)
                });
                
                //默认第一个选中
                if (i == 0)
                    $me.trigger('touchstart');
            });
        }
    });
    /**
     * function位置按逻辑顺序排列,即当前函数调用到的函数在下面,这样就可以一直往下翻
     */
    var Root = r.createClass({
        getInitialState: function () {
            return {
                inputList: [],
                taskList: [],
                nextTask: [], //下一步骤
                history: [], //流程日志
                attaches: [], //附件
                attachUrls: [], //附件PDF跳转的链接
                maskClass: '', //日志mask的类值,可为　active
                formVisible: '',
                formConVisible: '',
            }
        },
        componentWillMount: function () {
            var me = this;
            
            //非新增
            if (!isNew) {
                ajax({
                    data: {
                        orderId: orderId,
                    },
                }, lf.api.workflow.getValue, function (data) {
                    me.getFields(data);
                });
                
                //显示流程日志
                ajax({
                    data: {
                        orderId: orderId,
                    },
                    success: function (data) {
                        if (data.code != '200') {
                            appAlert('没有流程日志');
                            return;
                        }
                        var rows = data && data.dataList.map(function (data, i) {
                                return <DetailRow key={'datailRow-'+i} isApproval="true" data={data}/>
                            });
                        
                        me.setState({
                            history: <div className="task-processing-detail">{rows}</div>
                        });
                    },
                }, lf.api.workflow.history);
                
                //已完成不需要查找taskId
                if (flag != lf.approvalInfo.APPROVED)
                    ajax({
                        data: {
                            orderId: orderId,
                            staffId: lf.userInfo.id,
                        },
                        success: function (resp) {
                            ajaxData.taskId = resp.data && resp.data.id;
                        },
                    }, lf.api.workflow.currentTask)
                
            }
            else {
                me.getFields();
            }
            
            //下一步骤
            //非已完成
            if (flag == lf.approvalInfo.APPROVING)
                ajax({
                    data: {
                        staffId: lf.userInfo.id,
                        processId: processId,
                        taskName: taskName,
                    },
                    success: function (data) {
                        if (data.code != '200') {
                            //appAlert('数据异常');
                            location.reload();
                        }
                        
                        me.setState({
                            nextTask: <NextTask data={data.dataList}/>
                        })
                    },
                }, lf.api.workflow.nextTask);
        },
        /**
         * @param values 可选,对象
         */
        getFields: function (values) {
            var me = this;
            ajax({
                data: {
                    staffId: lf.userInfo.id,
                    processId: processId,
                    taskName: taskName || '',
                },
                success: function (data) {
                    if (data.code != '200') return;
                    
                    let attaches = values && values.taskAttachsJson ? JSON.parse(values.taskAttachsJson) : [];
                    
                    
                    me.setState({
                        inputList: me.inputListRender(data.dataList, values),
                        attaches: me.renderAttaches(attaches),
                        attachUrls: attaches,
                    })
                    
                    me.toPDFViewerFn();
                    
                }
            }, lf.api.workflow.getFields);
        },
        toPDFViewerFn: function () {
            let $pdfLink = $('.mui-table-view-cell'),
                data = this.state.attachUrls;
            
            $.each($pdfLink, function (i) {
                
                let url = PDF + data[i].fileUrl,
                    title = decodeURI(data[i].fileName),
                    $me = $(this);
                
                if (data[i].fileUrl.indexOf('.pdf') > -1) {
                    $me.off();
                    $me.on('tap', function () {
                        doAction(url, title);
                    })
                } else { //防止非PDF 的url跳转;
                    let $notPDF = $me.find('.flex-item.text-dot');
                    $notPDF.addClass('not-pdf');
                }
                
            })
        },
        renderAttaches: function (attaches) {
            return (
                attaches.map(function (data, i) {
                    return (
                        <div key={'key'+i} className="mui-table-view-cell flex attaches">
                            <p className="flex-item text-dot">{decodeURI(data.fileName)}</p>
                            <p className="flex-item text-dot">
                                {data.creatorName ? decodeURI(data.creatorName) : ''}
                            </p>
                        </div>
                    )
                })
            )
        },
        inputListRender: function (fieldList, values) {
            //log(values)
            return (
                fieldList.map(function (data, i) {
                    var type = data.type,
                        title = data.displayName,
                        name = data.name,
                        attr = data.attrMap,
                        isNeed = attr && attr.isNeed,
                        defaultValue = attr && attr.defaultValue,
                        value = values && values[name],
                        readonly = attr && (attr.readonly == 'true' || flag != lf.approvalInfo.APPROVING) ? true : false,
                        visibility = (isNew || (flag == lf.approvalInfo.APPROVING && !value))
                        && readonly && !defaultValue ? 'ele-hide' : '',
                        field;
                    
                    if (type == 'Detail') {
                        if (readonly) {
                            field = <textarea name={name} value={value} rows="10" readOnly/>
                        }
                        else {
                            field = <textarea className={isNeed == 'true' ?  "required" : ''} name={name}
                                              defaultValue={value}
                                              placeholder="请输入*"/>
                        }
                    }
                    else if (type == 'Radio') {
                        field = <Radio data={attr.data} defaultValue={attr.defaultValue} value={value} name={name}
                                       readonly={attr.readonly}/>
                    }
                    //还有Calendar类型?
                    else if (type == 'Calendar') {
                        //field = <button id="demo1" data-options="{}" class="btn mui-btn mui-btn-block">选择日期时间 ...</button>;
                        field = <DtPicker isNeed={isNeed} value={value} name={name} readonly={attr.readonly}/>
                        
                    }
                    //(type == 'String')
                    else if (type == 'String') {
                        var inputClass = ' text-right float-right ';
                        if (readonly)
                            field = <input className={inputClass} type="text" name={name} value={value || defaultValue}
                                           readOnly/>;
                        else
                            field =
                                <input className={isNeed == 'true' ?  "required" + inputClass  : inputClass} type="text"
                                       name={name} defaultValue={value || defaultValue} placeholder="请输入*"/>;
                        
                    }
                    else if (type == 'Table') {
                        //system
                        field = <div>{attr.header}</div>
                    }
                    
                    //页面布局重构
                    //input放在一行
                    if (type == 'String' || type == 'Calendar') {
                        return <div className="input-row">
                            <label className="title">{title}</label>
                            {field}
                        </div>
                        
                    }
                    
                    return (
                        <div key={'input-'+i} className={visibility + " white-bg margin-top"}>
                            <div className="title j-input-box">{title}</div>
                            {field}
                        </div>
                    )
                })
            )
        },
        render: function () {
            var state = this.state,
                btn = [],
                workflow = {aLinkClass: 'green', clickHandler: this.showHistory, text: '流程日志'},
                submit = {aLinkClass: 'green ', clickHandler: this.submit, text: '提交'};
            
            isNew ? btn.push(submit) :
                flag == lf.approvalInfo.APPROVING ? btn.push(workflow, submit) :
                    btn.push(workflow);
            
            return (
                <form className="approval approval-detail f2-bg" action="javascript:void(0);" ref="form">
                    {state.inputList}
                    <div className="white-bg margin-top">{state.attaches}</div>
                    {state.nextTask}
                    <div className="input-box  margin-top">
                        <FooterBtn data={btn}/>
                    </div>
                    <div className={this.state.maskClass + " mui-backdrop"}>
                        {this.state.history}
                    </div>
                </form>
            )
        },
        /**
         * 显示流程日志，点击的隐藏事件在DidMount里
         */
        showHistory: function () {
            this.setState({maskClass: 'active'});
        },
        componentDidMount: function () {
            var $mask = $('.mui-backdrop'),
                me = this;
            
            $mask.on('click', function () {
                me.setState({maskClass: ''});
            });
            
        },
        checkInput: function () {
            var flag = true,
                $requireds = $('.required');
            
            for (var i = 0; i < $requireds.length; i++) {
                var ele = $requireds[i],
                    type = ele.tagName,
                    name = ele.getAttribute('name'),
                    title = ele.previousElementSibling.textContent,
                    len = $requireds.eq(i).val().length,
                    msg = '不得超过';
                
                //这j8代码
                if (len < 1) {
                    flag = false;
                    break;
                }
                else if (type == 'INPUT' && len > 20) {
                    appAlert(title + msg + '20字');
                    return;
                }
                else if (type == 'TEXTAREA') {
                    if (name == 'content' && len > 2000) {
                        appAlert(title + msg + '2000字');
                        return;
                    }
                    else if (len > 200) {
                        appAlert(title + msg + '200字');
                        return;
                    }
                }
            }
            return flag;
        },
        /**
         * 下一步,提交
         */
        submit: function (e) {
            var flag = this.checkInput(),
                me = this;
            
            if (flag == undefined) return;
            if (flag == false) {
                appAlert('请完整填写文件');
                return;
            }
            
            if (!ajaxData.taskName) {
                appAlert('请选择下一步骤');
                return;
                
            }
            if (ajaxData.taskName != 'end' && !ajaxData.nextOperator) {
                appAlert('请选择下一步办理人');
                return;
            }

            var array = $('form').serializeArray(),
                params = {};
            
            for (var i = 0, len = array.length; i < len; i++) {
                var obj = array[i],
                    key = obj.name,
                    value = obj.value;
                params[key] = value;
            }
            
            ajax({
                type: 'POST',
                data: {
                    staffId: lf.userInfo.id,
                    processId: processId,
                    orderId: orderId || '',
                    taskName: ajaxData.taskName || taskName,
                    taskId: ajaxData.taskId,
                    assignee: ajaxData.assignee,
                    nextOperator: ajaxData.nextOperator, //id
                    params: params,
                    
                },
                success: function (data) {
                    if (data.code == '200') {
                        //prevent user from editing
                        lf.appJs.doClose();
                    }
                    else {
                        appAlert(data.desc, lf.appJs.doClose());
                    }
                },
            }, lf.api.workflow.startOrExecute)
        }
    });
    
    lf.bridgeJs.getUser(function () {
        r.render(
            <Root />,
            document.getElementById('root'), function () {
                mui.init();
            }
        )
    });
})(liefeng, React, mui);
